#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#define DEL_MODE 0666

#define FLUSHNONE 1
#define FLUSHLINE (1<<1)
#define FLUSHALL (1<<2)

myFILE* myfopen(const char* path , const char* mode)
{
    int fd = 0;
    int flag = 0;
    if(strcmp(mode,"r") == 0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag |= (O_WRONLY | O_CREAT | O_APPEND);
    }
    else 
    {
        // 这里只写三种情况
        // do nothing
    }

    if(flag & O_CREAT)
    {
        fd = open(path,flag,DEL_MODE);
    }
    else 
    {
        fd = open(path,flag);
    }

    if(fd < 0)
    {
        errno = 2; // 设置错误码
        return NULL;
    }
    
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    
    if(fp == NULL)
    {
        errno = 3;
        return NULL;
    }

    fp->fileno = fd;
    fp->end = 0;
    fp->flag = FLUSHLINE;
    return fp;
}

int myfwrite(const void *ptr,int size, int num,myFILE* stream)
{
    memcpy(stream->buffer+stream->end,ptr,num*size);
    stream->end+=num;

    if(stream->flag == FLUSHLINE &&  stream->end > 0 && stream->buffer[stream->end-1] == '\n')
    {
        myfflush(stream);
    }

    return 0;
}


int myfflush(myFILE* stream)                                              
{
    if(stream->end > 0)
    {
        write(stream->fileno,stream->buffer,stream->end);
    }
    
    stream->end = 0;
    return 0;
}                         


int myfclose(myFILE* fp)
{
    myfflush(fp);
    return close(fp->fileno);
}
